<template>
  <div class="blog-container">
    <!-- 顶部搜索栏 -->
    <div class="blog-header">
      <div class="search-bar">
        <input
            v-model="searchStr"
            placeholder="搜索文章..."
            class="search-input"
            @keyup.enter="handleSearch"
        />
        <button @click="handleSearch" class="search-btn">搜索</button>
        <button @click="handleReset" class="reset-btn">重置</button>
      </div>
      <button @click="showAddArticle = true" class="write-btn">写博客</button>
    </div>

    <!-- 文章列表 -->
    <div class="article-list">
      <div
          v-for="article in articles"
          :key="article.id"
          class="article-item"
          @click="handleArticleClick(article)"
      >
        <h3 class="article-title">{{ article.title }}</h3>
        <div class="article-meta">
          <span class="author">{{ article.userName || '未知作者' }}</span>
          <span class="date">{{ formatDate(article.createTime) }}</span>
          <span class="views">👁️阅读 {{ article.viewCount || 0 }}</span>
          <span class="likes">👍点赞 {{ article.likeCount || 0 }}</span>
        </div>
        <p class="article-summary">{{ getArticleSummary(article.content) }}</p>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
          class="page-btn"
      >
        上一页
      </button>
      <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
      <button
          :disabled="currentPage >= totalPages"
          @click="changePage(currentPage + 1)"
          class="page-btn"
      >
        下一页
      </button>
    </div>

    <!-- 写文章弹窗 -->
    <div v-if="showAddArticle" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h2>写博客</h2>
        <input
            v-model="newArticle.title"
            placeholder="文章标题"
            class="modal-input title-input"
        />
        <textarea
            v-model="newArticle.content"
            placeholder="文章内容"
            class="modal-textarea"
        ></textarea>
        <div class="modal-footer">
          <button @click="closeModal" class="cancel-btn">取消</button>
          <button @click="submitArticle" class="submit-btn">发布</button>
        </div>
      </div>
    </div>

    <!-- 文章详情弹窗 -->
    <div v-if="showArticleDetail" class="modal-overlay" @click="closeArticleDetail">
      <div class="modal-content article-detail-modal" @click.stop>
        <div class="modal-header">
          <h2>{{ currentArticle.title }}</h2>
          <button class="close-btn" @click="closeArticleDetail">×</button>
        </div>
        <div class="article-detail-meta">
          <span class="author">{{ currentArticle.userName || '未知作者' }}</span>
          <span class="date">{{ formatDate(currentArticle.createTime) }}</span>
          <span class="category" v-if="currentArticle.categoryName">分类： {{ currentArticle.categoryName }}</span>
          <span class="views">👁️阅读 {{ currentArticle.viewCount || 0 }}</span>
          <span class="likes">👍点赞 {{ currentArticle.likeCount || 0 }}</span>
        </div>
        <div class="article-detail-content">
          {{ currentArticle.content }}
        </div>
        <button
            @click="handleLike"
            :disabled="currentArticle.value && likedArticles.value && likedArticles.value.has(currentArticle.value.id)"
            :class="['like-btn', { liked: currentArticle.value && likedArticles.value && likedArticles.value.has(currentArticle.value.id) }]"
        >
          {{ currentArticle.value && likedArticles.value && likedArticles.value.has(currentArticle.value.id) ? '已点赞' : '点赞' }}
        </button>
        <div class="modal-footer">
          <button @click="closeArticleDetail" class="cancel-btn">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import articleApi from '../api/article'
import categoryApi from '../api/category'
import auth from '../utils/auth'

// 响应式数据
const articles = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchStr = ref('')
const showAddArticle = ref(false)
const showArticleDetail = ref(false)
const currentArticle = ref({})
const likedArticles = ref(new Set()) // 存储已点赞的文章ID

// 新文章数据
const newArticle = ref({
  title: '',
  content: ''
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 初始化加载文章列表
onMounted(() => {
  loadArticles()
})

// 加载文章列表
const loadArticles = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    // 如果有搜索关键词，则添加到参数中
    if (searchStr.value.trim()) {
      params.str = searchStr.value.trim()
    }

    const response = await articleApi.getArticleList(params)
    if (response.code === 200 && response.data) {
      articles.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      console.error('加载文章列表失败:', response.msg)
    }
  } catch (error) {
    console.error('加载文章列表出错:', error)
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadArticles()
}

// 处理重置
const handleReset = () => {
  searchStr.value = ''
  currentPage.value = 1
  loadArticles()
}

// 切换页码
const changePage = (page) => {
  currentPage.value = page
  loadArticles()
}

// 获取文章摘要
const getArticleSummary = (content) => {
  if (!content) return ''
  // 截取前100个字符作为摘要
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}

// 处理文章点击 - 实现后端阅读量增加功能
const handleArticleClick = async (article) => {
  // 显示文章详情
  currentArticle.value = {...article}
  showArticleDetail.value = true

  // 重点是调用后端API来增加数据库中的阅读量
  if (article) {
    try {
      const articleId = article.id || 1; // 使用默认值1作为示例

      await articleApi.addViewCount(articleId)

      // 调用后端接口获取文章类别
      if (article.categoryId) {
        const categoryResponse = await categoryApi.getCategoryById(article.categoryId)
        if (categoryResponse.code === 200 && categoryResponse.data) {
          currentArticle.value.categoryName = categoryResponse.data.name
        }
      }

      // 这里不再主动更新前端显示，让数据从后端重新加载时自然更新
    } catch (error) {
    }
  }
}

// 处理点赞和取消点赞
const handleLike = async () => {
  const articleId = currentArticle.value.id
  const isLiked = likedArticles.value.has(articleId)

  try {
    // 从auth工具获取当前用户的userId
    const userId = auth.getUserId() || 1 // 默认值1作为示例

    // 调用后端接口，假设后端接口可以根据参数处理点赞和取消点赞
    // 这里我们传递一个额外的isCancel参数来标识是否取消点赞
    const response = await articleApi.likeArticle({
      userId,
      articleId,
      isCancel: isLiked
    })

    if (response.code === 200) {
      if (isLiked) {
        // 取消点赞成功，从已点赞集合中移除，并减少点赞数
        likedArticles.value.delete(articleId)
        currentArticle.value.likeCount = Math.max(0, (currentArticle.value.likeCount || 0) - 1)
      } else {
        // 点赞成功，添加到已点赞集合，并增加点赞数
        likedArticles.value.add(articleId)
        currentArticle.value.likeCount = (currentArticle.value.likeCount || 0) + 1
      }
    } else {
      console.error(isLiked ? '取消点赞失败:' : '点赞失败:', response.msg)
    }
  } catch (error) {
    console.error(isLiked ? '取消点赞请求出错:' : '点赞请求出错:', error)
  }
}

// 关闭文章详情弹窗
const closeArticleDetail = () => {
  showArticleDetail.value = false
  currentArticle.value = {}
}

// 关闭弹窗
const closeModal = () => {
  showAddArticle.value = false
  // 重置表单
  newArticle.value = {
    title: '',
    content: ''
  }
}

// 提交文章
const submitArticle = async () => {
  if (!newArticle.value.title.trim() || !newArticle.value.content.trim()) {
    alert('请填写标题和内容')
    return
  }

  try {
    const articleVO = {
      title: newArticle.value.title,
      content: newArticle.value.content,
      // 获取当前用户ID，需要根据实际的auth工具调整
      userId: auth.getUserId() || 1
    }

    const response = await articleApi.addArticle(articleVO)
    if (response.code === 200) {
      alert('发布成功')
      closeModal()
      // 重新加载文章列表
      loadArticles()
    } else {
      alert('发布失败: ' + response.msg)
    }
  } catch (error) {
    console.error('发布文章失败:', error)
    alert('发布失败，请稍后重试')
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.blog-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 顶部搜索栏 */
.blog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-bar {
  display: flex;
  flex: 1;
  max-width: 600px;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 16px;
}

.search-btn {
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  font-size: 16px;
}

.reset-btn {
  margin-left: 10px;
  padding: 10px 20px;
  background: #67C23A;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.reset-btn:hover {
  background: #5daf34;
}

.search-btn:hover {
  background: #0056b3;
}

.write-btn {
  padding: 10px 25px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-left: 20px;
}

.write-btn:hover {
  background: #218838;
}

/* 文章列表 */
.article-list {
  margin-bottom: 30px;
}

.article-item {
  padding: 20px;
  margin-bottom: 20px;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.article-item:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

.article-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.article-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.article-summary {
  color: #666;
  line-height: 1.6;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.page-btn {
  padding: 8px 16px;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:hover:not(:disabled) {
  background: #e9ecef;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  padding: 30px;
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

/* 文章详情样式 */
.article-detail-modal {
  width: 90%;
  max-width: 900px;
  max-height: 90vh;
}

.article-detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
  font-size: 14px;
  color: #666;
}

.article-detail-meta .category {
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.article-detail-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.like-btn {
  padding: 10px 30px;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.like-btn:hover:not(:disabled) {
  background: #ff3742;
  transform: translateY(-2px);
}

.like-btn:disabled {
  background: #c8c8c8;
  cursor: not-allowed;
  transform: none;
}

.like-btn.liked {
  background: #ff6b81;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

.modal-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 16px;
}

.title-input {
  font-size: 18px;
  font-weight: 500;
}

.modal-textarea {
  width: 100%;
  height: 300px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 16px;
  resize: vertical;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .submit-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.cancel-btn {
  background: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background: #5a6268;
}

.submit-btn {
  background: #28a745;
  color: white;
}

.submit-btn:hover {
  background: #218838;
}
</style>